﻿using System.Web.Mvc;

// Allows Ajax results to perform a redirection
// Ref: http://craftycodeblog.com/2010/05/15/asp-net-mvc-ajax-redirect/
public class AjaxFriendlyController : Controller
{
    protected override RedirectResult Redirect(string url)
    {
        return new AjaxAwareRedirectResult(url);
    }
}

public class AjaxAwareRedirectResult : RedirectResult
{
    public AjaxAwareRedirectResult(string url)
        : base(url)
    {
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);

            JavaScriptResult result = new JavaScriptResult()
            {
                // Using this method to allow the iframe to pass the redirect to the parent window, otherwise iframe redirects inside itself
                Script = "window.parent.location.href='" + destinationUrl + "';"
                // Script = "window.location='" + destinationUrl + "';" // Old method
            };
            result.ExecuteResult(context);
        }
        else
            base.ExecuteResult(context);
    }
}